package com.demo.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.demo.api.PushTemp;
import com.demo.util.PropertiesHelper;
import com.demo.util.Upload;
import com.demo.vo.EventVO;
import com.demo.vo.ResultVO;
import com.jfinal.kit.StringKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.weixin.sdk.api.ApiResult;

import org.apache.log4j.Logger;

import java.util.List;
import java.util.Properties;

/**
 * Created by tianzhen.wtz on 2015/4/8 0008.
 * 类说明：
 */
public class UpdateRecordUtils {

    public static String AppId = "";
    public static String AppSecret = "";
    public static String charset = "";
    public static String carurl = "";
    public static String carkey = "";
    public static String temp = "";

    public static int cardate = 30;

    static {
        Properties r = PropertiesHelper.loadProperty("/weixin.properties");
        if (!r.isEmpty()) {
            try {
                AppId = r.getProperty("AppId");
                AppSecret = r.getProperty("AppSecret");
                charset = r.getProperty("charset");
                carurl = r.getProperty("carurl");
                carkey = r.getProperty("carkey");
                temp=r.getProperty("tempid");
                cardate = Integer.parseInt(r.getProperty("cardate"));
            } catch (Exception e) {
                Logger.getLogger(Upload.class).error("无法读取参数", e);
            }
        } else {
            Logger.getLogger(Upload.class).error("无法读取 weixin.properties");
        }
    }


    /**
     * 获取记录
     * @param param 请求参数
     * @param hphm 车牌
     * @param cxrq 当前日期
     * @param bs  标示
     * @return boolean
     */
    public static boolean updateRecord(String param,String hphm,String cxrq,String bs,String openid){
        String url = carurl + param;// url为请求的api接口地址
        System.out.println("==========" + url);
        // 通过接口查询对应车的违章记录
			String jsonResult = com.demo.kits.HttpKit.get(url, "utf-8");
//        String jsonResult = "{\n" +
//                "error_code: 2,\n" +
//                "reason: \"KeyError\",\n" +
//                "result: null\n" +
//                "}";
        System.out.println("-----" + jsonResult);
        // String jsonResult = FileKit
        // .getContentFromFile("G:\\workspace\\wzcx\\wzcx\\src\\jsons.txt");

        JSONObject jsonTexts = (JSONObject) JSON.parse(jsonResult);
        System.out.println("===============" + jsonTexts);
        String errorcode = "";
        if (StringKit.notBlank(jsonTexts.getString("error_code"))) {
            errorcode = jsonTexts.getString("error_code");
        }
        // 假如有违章记录，则记录在本地的数据库中
        if (errorcode.equals("0")) {
            // 表示查询过 数据
            Record log = new Record();
            log.set("hphm", hphm);
            log.set("cxrq", cxrq);
            // 获取车辆信息
            Db.save("t_querylog", log);
            // 假如有违章 更新标示
            // Db.update("update t_eventlist set handled ='已处理' where hphm='"+
            // hphm + "'");
            String resultJsonText = jsonTexts.getString("result");

            ResultVO result = JSON.parseObject(resultJsonText,
                    ResultVO.class);
            System.out.println("===============" + result);
            if (result != null) {
                List<EventVO> events = result.getLists();
                System.out.println("===============" + events);

                if (events != null) {
                    // Db.deleteById("t_eventlist", "hphm", hphm);
                    for (EventVO each : events) {
                        Record xx = new Record();
                        xx.set("date", each.getDate());
                        xx.set("area", each.getArea());
                        xx.set("act", each.getAct());
                        xx.set("code", each.getCode());
                        xx.set("fen", each.getFen());
                        xx.set("money", each.getMoney());
                        xx.set("handled", each.getHandled());
                        xx.set("payno", each.getPayno());
                        xx.set("longitude", each.getLongitude());
                        xx.set("latitude", each.getLatitude());
                        xx.set("latitude", each.getLatitude());
                        xx.set("hphm", hphm);
                        xx.set("cxrq", cxrq);
                        // xx.set("city", city);

                        // 如果有此违章 则 更新
                        List<Record> list = Db
                                .find("select * from t_eventlist where date ='"
                                        + each.getDate()
                                        + "'   and hphm='"
                                        + hphm + "' ");
                        if (list.size() > 0 && list != null) {
                            System.out.println("=====listisze============="
                                    + list.size());
                            xx.set("id", list.get(0).get("id"));
                            Db.update("t_eventlist", xx);
                        } else {
                            xx.remove("id");
                            Db.save("t_eventlist", xx);
                        }
                        //填充模板消息
                        if(bs.equals("1") &&StringKit.notBlank(openid)){
                        	String contetn=each.getDate()+"在"+each.getArea()+each.getAct()+"扣："+each.getFen()+"罚款："+each.getMoney();
                    		ApiResult apiResult = PushTemp.pushWxTemp(openid,temp,url,contetn);

                        }
                        // event.save();
                    }
                }
            }
        }
        return Boolean.TRUE;
    }

	public static void main(String args[]) {
		String openid="oh-oduCSPuENS4e1CetXL8hzsSGA";
		String content="aaaaaaaaaaaaaaaaaaaaaaaaa";
		String url="";
		// 调用微信模板填充内容。传入参数openid 
		ApiResult apiResult = PushTemp.pushWxTemp(openid,temp,url,content);
		System.out.println(apiResult.getJson());
	}
	
}
